<template>
  <a-modal v-model:visible="visible" :title="title" unmount-on-close @before-ok="onOk">
    <a-form ref="formRef" :model="form" size="medium" auto-label-width>
      <a-form-item
        label="登录账号"
        field="username"
        :rules="[
          { required: true, message: '请输入登录账号' },
          { min: 2, max: 10, message: '长度在 2 - 10个字符' }
        ]"
        :validate-trigger="['change', 'input', 'blur', 'focus']"
      >
        <a-input :disabled="!!form.id" placeholder="请输入登录账号" v-model="form.username" allow-clear></a-input>
      </a-form-item>
      <a-form-item
        label="用户昵称"
        field="name"
        :rules="[
          { required: true, message: '请输入用户昵称' },
          { min: 2, max: 10, message: '长度在 2 - 10个字符' }
        ]"
        :validate-trigger="['change', 'input', 'blur', 'focus']"
      >
        <a-input placeholder="请输入用户昵称" v-model="form.name" allow-clear></a-input>
      </a-form-item>
      <a-form-item
        label="登录密码"
        field="password"
        :rules="[
          { required: !form.id, message: '请输入登录密码' },
          { min: 2, max: 10, message: '长度在 2 - 10个字符' }
        ]"
        :validate-trigger="['change', 'input', 'blur', 'focus']"
      >
        <a-input-password placeholder="请输入登录密码" v-model="form.password" allow-clear></a-input-password>
      </a-form-item>
      <a-form-item label="用户状态" field="status" :rules="[{ required: true, message: '请选择用户状态' }]">
        <a-radio-group v-model="form.status">
          <a-radio :value="1">启用</a-radio>
          <a-radio :value="0">不启用</a-radio>
        </a-radio-group>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { adminUserAdd, adminUserEdit } from '@/apis'
import { Message } from '@arco-design/web-vue'
const emit = defineEmits(['getTableData'])

const title = computed(() => (form.id ? '编辑用户' : '新增用户'))
const visible = ref(false)
const formRef = ref()

const form = reactive({
  id: undefined,
  name: '',
  username: '',
  password: '',
  status: 0
})

const addOrEdit = (userItem) => {
  form.id = userItem?.id || undefined
  form.name = userItem?.name || ''
  form.username = userItem?.username || ''
  form.password = userItem?.password || ''
  form.status = userItem?.status || 0
  visible.value = true
}

const onOk = async () => {
  const validateResult = await formRef.value?.validate()
  if (validateResult) return false
  const api = form.id ? adminUserEdit : adminUserAdd
  await api(form)
  Message.success('操作成功')
  emit('getTableData')
  return true
}

defineExpose({ addOrEdit })
</script>
